<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    const Compare = {
      LESS_THAN: -1,
      BIGGER_THAN: 1
    };
    function defaultCompare(a, b) {
      if (a === b) {
        return 0;
      }
      return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN;
    }
    class SortedLinkedList extends LinkedList {//LinkedList这个类可以见https://www.cnblogs.com/MySweetheart/p/13212220.html
      constructor(equalsFn = defaultEquals, compareFn = defaultCompare) {
        super(equalsFn);
        this.compareFn = compareFn;
      }
      insert(element, index = 0) {
        if (this.isEmpty()) {
          return super.insert(element, 0);
        }
        const pos = this.getIndexNextSortedElement(element);
        return super.insert(element, pos);
      }
      getIndexNextSortedElement(element) {
        let current = this.head;
        let i = 0;
        for (; i < this.size() && current; i++) {
          const comp = this.compareFn(element, current.element);
          if (comp == Compare.LESS_THAN) {
            return i;
          }
          current = current.next;
        }
        return i;
      }
    }
    复制代码
  </script>
</body>

</html>